/*年轻人，只管向前看，不要管自暴自弃者的话*/
package com.ndk.head.uvc.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * create by itz on 2024-11-25 14:36
 * desc :
 **/
public class BitmapUtil {
    // 根据图片路径获取 Bitmap
    public static Bitmap getBitmapFromPath(String imagePath) {
        return BitmapFactory.decodeFile(imagePath);
    }

    // 将 Bitmap 转换为 byte 数组
    public static byte[] convertBitmapToByteArray(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        return stream.toByteArray();
    }

    // 在指定坐标范围内给 Bitmap 图片绘制红色框
    public static Bitmap drawRedBoxOnBitmap(Bitmap originalBitmap, int left, int top, int right, int bottom) {
        Bitmap bitmapWithBox = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), originalBitmap.getConfig());
        Canvas canvas = new Canvas(bitmapWithBox);

        // 绘制原始 Bitmap
        canvas.drawBitmap(originalBitmap, 0, 0, null);

        // 创建画笔
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5);

        // 绘制红色框
        canvas.drawRect(left, top, right, bottom, paint);

        return bitmapWithBox;
    }

    // 保存 Bitmap 到本地存储
    public static void saveBitmap(Bitmap bitmap, String filename) {
        File file = new File(filename);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
